package com.example.lt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lt.constant.MessageConstant;
import com.example.lt.exception.SupportFailException;
import com.example.lt.mapper.UserSupportMapper;
import com.example.lt.pojo.entity.UserSupport;
import com.example.lt.result.Result;
import com.example.lt.service.UserSupportService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @Author 小涛Tao
 * @Date: 2024/06/04/14:23
 * version 1.0 注释：
 **/
@Service
@RequiredArgsConstructor
public class UserSupportServiceImpl extends ServiceImpl<UserSupportMapper, UserSupport> implements UserSupportService {

    private final UserSupportMapper userSupportMapper;

    /**
     * 检查当前用户是否点赞了当前评论
     * @param userSupport
     * @return
     */
    public Result checkSupport(UserSupport userSupport) {
        // TODO 后续这里要把这个查询调优，后面两个方法也是
        QueryWrapper<UserSupport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", userSupport.getCommentId());
        queryWrapper.eq("user_id", userSupport.getUserId()).lambda();
        if (userSupportMapper.selectCount(queryWrapper) > 0) {
            return Result.success(MessageConstant.CANCEL_SUPPORT, true);
        } else {
            return Result.success(MessageConstant.SUPPORT, false);
        }
    }

    /**
     * 删除当前用户对当前评论的点赞
     * @param userSupport
     * @return
     */
    public Result delete(UserSupport userSupport) {
        // TODO 后期要改，把更新评论总点赞数和点赞记录的添加和删除写在一起，保障事务的一致性
        QueryWrapper<UserSupport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", userSupport.getCommentId());
        queryWrapper.eq("user_id", userSupport.getUserId()).lambda();
        if (userSupportMapper.delete(queryWrapper) > 0) {
            return Result.success(MessageConstant.CANCEL_SUPPORT);
        } else {
            throw new SupportFailException(MessageConstant.CANCEL_SUPPORT_FAIL);
        }
    }

    /**
     * 根据评论id删除点赞表中的记录
     * @param commentId
     */
    public void deleteByComId(Integer commentId) {
        QueryWrapper<UserSupport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", commentId);
        userSupportMapper.delete(queryWrapper);
    }

    /**
     * 添加当前用户对当前评论的点赞
     * @param userSupport
     * @return
     */
    public Result insert(UserSupport userSupport) {
        if (userSupportMapper.insert(userSupport) > 0) {
            return Result.success(MessageConstant.SUPPORT);
        } else {
            throw new SupportFailException(MessageConstant.SUPPORT_FAIL);
        }
    }

}
